import React, { Component } from 'react'
// import axios from 'axios';
import PubSub from 'pubsub-js'

export default class Search extends Component {
  search = async () => {
    // 获取用户的输入（连续解构赋值+重命名）
    const { keyWordElement: {value: keyWord} } = this
    // 发送请求前通知List更新状态
    PubSub.publish('stateObj', {isFirst: false, isLoading: true});

    // 发送网络请求---使用axios发送
    /* axios.get(`/api1/j/search_subjects?type=tv&tag=${encodeURI(keyWord)}&page_limit=50&page_start=0`).then((res) => {
      // 请求发送后通知List更新状态
      let {data:{subjects: users}} = res
      PubSub.publish('stateObj', { isLoading: false, users})
    }, err => {
      // 请求失败后通知List更新状态
      PubSub.publish('stateObj', { isLoading: false, err})
    }) */

    // 发送网络请求---使用fetch发送（未优化）
    /* fetch(`/api1/j/search_subjects?type=tv&tag=${encodeURI(keyWord)}&page_limit=50&page_start=0`).then(
      res => {
        console.log(res, "联系服务器成功了")
        return res.json()
      }, 
      err => {
        console.log(err, "联系服务器失败了")
        return new Promise(() => {})
      }
    ).then(
      res => {
        console.log(res, "获取数据成功了")
      },
      err => {
        console.log(err, "获取数据失败了")
      }
    ).catch(    // 统一处理错误
      err => {
        console.log(err, "请求出错")
      }
    ) */

    // 发送网络请求---使用fetch发送（优化）
    /* fetch(`/api1/j/search_subjects?type=tv&tag=${encodeURI(keyWord)}&page_limit=50&page_start=0`).then(
      res => {
        console.log(res, "联系服务器成功了")
        return res.json()
      }
    ).then(
      res => {
        console.log(res, "获取数据成功了")
      }
    ).catch(    // 统一处理错误
      err => {
        console.log(err, "请求出错")
      }
    ) */

    // 发送网络请求---使用fetch发送（极简优化）
    try {
      const response = await fetch(`/api1/j/search_subjects?type=tv&tag=${encodeURI(keyWord)}&page_limit=50&page_start=0`)
      const data = await response.json()
      console.log(data)
      let { subjects:users } = data
      PubSub.publish('stateObj', { isLoading: false, users})
    } catch (err) {
      console.log(err)
      PubSub.publish('stateObj', { isLoading: false, err})
    }
    
  }
  render() {
    return (
      <section className='jumbotron'>
        <h3 className='jumbotron-heading'>搜索github用户</h3>
        <div>
          <input ref={ c => this.keyWordElement = c } type="text" placeholder="输入关键词点击搜索" />
          <button onClick={this.search}>搜索</button>
        </div>
      </section>
    )
  }
}
